var u = navigator.userAgent.toLowerCase();
var isFirefox = u.indexOf('firefox') > -1;
var addEvent =  function(el, type, fn, capture) {
    if (type === "mousewheel" && isFirefox) {
        type = "DOMMouseScroll";
    }
    el.addEventListener(type, function(e) {
        var evt = e || window.event
        var type = evt.type;
        if (type == "DOMMouseScroll" || type == "mousewheel") {
            evt.delta = evt.wheelDelta ? evt.wheelDelta / 120 : -(evt.detail || 0) / 3;
        }

        if (evt.delta) {
            fn.call(this, evt);
        }
    }, capture || false);
};

function addClass(element, className) {

    if (element.classList) {
        className.split(' ').forEach(function(c) {
            element.classList.add(c);
        })
    } else {
        element.className += ' ' + className;
    }

}

function removeClass(element, className) {

    if (element.classList) {
        className.split(' ').forEach(function(c) {
            element.classList.remove(c);
        })
    } else {
        element.className = element.className.replace(new RegExp('(^|\\b)' + className.split(' ').join('|') + '(\\b|$)', 'gi'), ' ');
    }

}

// 查找元素中的动画子元素的函数
function findAnimatedElements(element) {
    // 首先查找直接的animated类元素
    var directAnimated = element.querySelectorAll(":scope > .animated");
    if (directAnimated.length > 0) {
        console.log('Found direct animated elements:', directAnimated);
        return directAnimated;
    }
    
    // 查找嵌套在wrapper元素中的animated元素（针对文本、图片、按钮等组件）
    var wrapperElements = element.querySelectorAll(":scope > .w-text-wrapper, :scope > .w-image-wrapper, :scope > .w-button-wrapper");
    if (wrapperElements.length > 0) {
        var wrappedAnimated = [];
        for (var i = 0; i < wrapperElements.length; i++) {
            var wrapper = wrapperElements[i];
            // 在wrapper中查找包含animated类的直接子元素
            var animatedChildren = wrapper.querySelectorAll(":scope > .animated");
            for (var j = 0; j < animatedChildren.length; j++) {
                wrappedAnimated.push(animatedChildren[j]);
            }
        }
        if (wrappedAnimated.length > 0) {
            console.log('Found wrapped animated elements:', wrappedAnimated);
            return wrappedAnimated;
        }
    }
    
    // 如果没有直接的animated元素，查找嵌套的animated元素
    var nestedAnimated = element.querySelectorAll(".animated");
    console.log('Found nested animated elements:', nestedAnimated);
    return nestedAnimated;
}

var FullPage = function(selector,option) {
    this.parent = typeof selector === "string" ? document.querySelector(selector) : selector;
    this.parent.style.visibility = "visible";
    var noop = function () { };
    this.beginToPage = option.beginToPage || noop;
    this.leavePage = option.leavePage || noop;
    this.stepHeight = this.parent.clientHeight;
    var children = this.parent.childNodes,
        len = children.length,
        i = 0;
    this.length = 0;
    this.children = [];
    for (; i < len; i++) {
        var child = children[i];
        if (child.nodeType !== 3) {
            child.style.height = this.stepHeight + "px";
            this.length++;
            // 使用新的查找函数查找动画元素
            var transitionChildren = findAnimatedElements(child);
            console.log('Transition children for page', i, ':', transitionChildren);
            this.children.push({child:child,transitionChildren:transitionChildren});
        }
    }

    this.duration = 600;
    this.timeoutArr = [];
    this.currentPage = 0;
    this.moving = false;
    this._transitionInit();

    var self = this;
    console.log('FullPage initialized with', this.length, 'pages');

    // 添加触摸事件处理
    var startY = 0;
    var currentY = 0;
    var isDragging = false;

    this.parent.addEventListener('touchstart', function(e) {
        if (self.moving) return;
        startY = e.touches[0].clientY;
        currentY = startY;
        isDragging = true;
        self.parent.style.transition = 'none';
    }, { passive: true });

    this.parent.addEventListener('touchmove', function(e) {
        if (!isDragging) return;
        currentY = e.touches[0].clientY;
        var deltaY = currentY - startY;
        var translateY = -self.currentPage * self.stepHeight + deltaY;
        self.parent.style.transform = 'translateY(' + translateY + 'px)';
        e.preventDefault();
    }, { passive: false });

    this.parent.addEventListener('touchend', function() {
        if (!isDragging) return;
        isDragging = false;
        
        var deltaY = currentY - startY;
        if (Math.abs(deltaY) < 30) {
            // 回到当前页
            self.to(self.currentPage);
        } else if (deltaY > 0) {
            // 上一页
            self.prev();
        } else {
            // 下一页
            self.next();
        }
    });

    // 鼠标滚轮事件保持不变
    addEvent(this.parent,"mousewheel" ,function (evt) {
        if(self.moving) return;
        self.moving = true;
        if(evt.delta>0 ){
            self.prev();
        }else {
            self.next();
        }
    });
};

FullPage.prototype = {
    _transitionInit:function(){
        console.log('Initializing transition');
        var i = 1 ,
            len = this.children.length;
        for(;i<len;i++){
            this._outPage(i);
        }
        this._toPage(0);
    },
    _toPage:function(index){
        console.log('Going to page:', index);
        var ttcs = this.children[index].transitionChildren;
        var  i = 0;
        var tLen = ttcs.length;
        console.log('Transition children count:', tLen);
        
        // 检查是否有动画元素
        if (tLen > 0) {
            console.log('Starting animations for page:', index);
            try {
                for (; i < tLen; i++) {
                    var node = ttcs[i];
                    console.log('Processing node:', node);
                    var delay = parseInt(node.getAttribute("data-delay")) || 0;
                    var showClass = node.getAttribute("data-show");
                    console.log('Node attributes - delay:', delay, 'showClass:', showClass);
                    
                    // 检查节点是否存在
                    if (!node) {
                        console.error('Animation node is null or undefined');
                        continue;
                    }
                    
                    node.style.visibility = "hidden";
                    var timeout = setTimeout((function(n,s){
                        return function(){
                            try {
                                console.log('Making node visible and applying animations');
                                n.style.visibility = "visible";
                                s&&addClass(n,s);
                            } catch (error) {
                                console.error('Error applying animations to node:', error);
                            }
                        }
                    })(node,showClass),delay);
                    this.timeoutArr.push(timeout);
                    
                    // 安排强调动画（如果有）
                    var emphasisDelay = parseInt(node.getAttribute("data-emphasis-delay")) || 1000;
                    var emphasisClass = node.getAttribute("data-emphasis");
                    if (emphasisClass) {
                        var emphasisTimeout = setTimeout((function(n, s, e) {
                            return function() {
                                try {
                                    // 移除入场动画类
                                    s && removeClass(n, s);
                                    // 添加强调动画类
                                    addClass(n, e);
                                    
                                    // 设置强调动画重复次数
                                    var emphasisCount = node.getAttribute("data-emphasis-count") || "infinite";
                                    n.style.animationIterationCount = emphasisCount;
                                    console.log('Emphasis animation applied:', emphasisClass);
                                } catch (error) {
                                    console.error('Error applying emphasis animation:', error);
                                }
                            }
                        })(node, showClass, emphasisClass), emphasisDelay);
                        this.timeoutArr.push(emphasisTimeout);
                    }
                    
                    // 安排退场动画（如果有）
                    var outDelay = parseInt(node.getAttribute("data-out-delay")) || 28000; // 默认28秒后开始退场
                    var outClass = node.getAttribute("data-out");
                    if (outClass) {
                        var outTimeout = setTimeout((function(n, s, o, e) {
                            return function() {
                                try {
                                    // 移除入场或强调动画类
                                    s && removeClass(n, s);
                                    e && removeClass(n, e);
                                    // 添加退场动画类
                                    addClass(n, o);
                                    console.log('Out animation applied:', outClass);
                                    
                                    // 监听退场动画结束事件
                                    n.addEventListener('animationend', function onAnimationEnd() {
                                        try {
                                            // 移除事件监听器，避免重复触发
                                            n.removeEventListener('animationend', onAnimationEnd);
                                            // 清理退场类并隐藏元素
                                            try { removeClass(n, o); } catch(e){ console.warn('removeClass failed', e); }
                                            n.style.visibility = "hidden";
                                            console.log('Out animation ended and element hidden');

                                            // 在短延时后，重新触发入场动画（移除可能残留的类后再添加showClass）
                                            if (s) {
                                                setTimeout(function() {
                                                    try {
                                                        // 保证入场类在未旋转容器上被重新添加，从而重新执行入场动画
                                                        removeClass(n, o);
                                                        removeClass(n, e);
                                                        n.style.visibility = "visible";
                                                        addClass(n, s);
                                                        console.log('Re-triggered enter animation:', s);
                                                    } catch (err) {
                                                        console.error('Error re-triggering enter animation:', err);
                                                    }
                                                }, 80);
                                            }
                                        } catch (error) {
                                            console.error('Error handling animation end:', error);
                                        }
                                    });
                                } catch (error) {
                                    console.error('Error applying out animation:', error);
                                }
                            }
                        })(node, showClass, outClass, emphasisClass), outDelay);
                        this.timeoutArr.push(outTimeout);
                    }
                }
                console.log('All animations started successfully for page:', index);
            } catch (error) {
                console.error('Error starting animations for page:', index, error);
            }
        } else {
            console.log('No transition children found for page:', index);
        }
    },
    _outPage:function(index){
        console.log('Out page:', index);
        var ltcs = this.children[index].transitionChildren;
        var lLen = ltcs.length,
            i = 0;
        if (lLen > 0) {
            for (; i < lLen; i++) {
                var node = ltcs[i];
                var showClass = node.getAttribute("data-show");
                var emphasisClass = node.getAttribute("data-emphasis");
                var outClass = node.getAttribute("data-out");
                
                console.log('Node classes - show:', showClass, 'emphasis:', emphasisClass, 'out:', outClass);
                
                try {
                    // 清除所有动画类
                    showClass&&removeClass(node,showClass);
                    emphasisClass&&removeClass(node,emphasisClass);
                    outClass&&removeClass(node,outClass);
                    
                    // 重置动画迭代次数
                    node.style.animationIterationCount = "";
                    
                    // 显示元素（确保下一页动画能正常显示）
                    node.style.visibility = "hidden";
                } catch (error) {
                    console.error('Error resetting animations for node:', error);
                }
            }
        }

        // 清除所有定时器
        while (this.timeoutArr.length > 0) {
            clearTimeout(this.timeoutArr[0]);
            this.timeoutArr.shift();
        }
    },
    _transition: function (leaveIndex, toIndex) {
        this._outPage(leaveIndex);
        this._toPage(toIndex);
    },
    next: function () {
        var index = this.currentPage + 1;

        if (index > this.length - 1) {
            index = this.length - 1;
            this.moving = false;
            return;
        }
        this.to(index);
    },
    prev: function () {
        var index = this.currentPage - 1;

        if (index < 0) {
            index = 0;
            this.moving = false;
            return;
        }
        this.to(index);
    },
    to: function (index, option) {
        option = option || {};
        console.log('Attempting to navigate to page:', index, 'Current moving state:', this.moving);
        if (index < 0 || index >= this.length || this.moving) {
            console.log('Navigation blocked - invalid index or already moving');
            this.moving = false;
            return;
        }

        var prevPage = this.currentPage;
        this.currentPage = index;
        console.log('Navigating from page', prevPage, 'to page', index);

        this.leavePage.call(this, prevPage);
        this.beginToPage.call(this, index);
        this._transition(prevPage, index);

        // 使用CSS transition实现动画
        this.parent.style.transition = 'transform ' + this.duration + 'ms ease';
        this.parent.style.transform = 'translateY(' + (-index * this.stepHeight) + 'px)';
        console.log('Applied transform for page transition:', -index * this.stepHeight + 'px');

        // 动画结束后触发回调
        var self = this;
        setTimeout(function() {
            console.log('Transition completed, resetting moving state');
            self.moving = false;
            if (option.animationEnd) {
                console.log('Executing animationEnd callback');
                option.animationEnd();
            }
        }, this.duration);
    }
};

export default FullPage